package com.bum.sock.poll.servlet.socket;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.comet.CometEvent;
import org.apache.catalina.comet.CometProcessor;

import com.bum.sock.poll.bo.Loader;
import com.bum.sock.poll.bo.MessageBO;

public class SocketServlet extends HttpServlet implements CometProcessor {
	private static final long		serialVersionUID	= 1L;

	protected transient MessageBO	messageBO			= null;

	@Override
	public void init() throws ServletException {
		messageBO = Loader.getBean("messageBO");

		Thread messageSenderThread = new Thread(messageBO, "MessageBO[" + getServletContext().getContextPath() + "]");
		messageSenderThread.setDaemon(true);
		messageSenderThread.start();
	}

	@Override
	public void destroy() {
		messageBO.destroy();
		messageBO = null;
	}

	@Override
	public void event(CometEvent event) throws IOException, ServletException {
		if (event.getEventType() == CometEvent.EventType.BEGIN) {
			messageBO.begin(event);
		} else if (event.getEventType() == CometEvent.EventType.ERROR) {
			messageBO.error(event);
		} else if (event.getEventType() == CometEvent.EventType.END) {
			messageBO.end(event);
		} else if (event.getEventType() == CometEvent.EventType.READ) {
			HttpServletRequest request = event.getHttpServletRequest();
			InputStream is = request.getInputStream();
			byte[] buf = new byte[512];
			while (is.available() > 0) {
				int n = is.read(buf);
				if (n < 0) {
					messageBO.end(event);
					return;
				}
			}
		}
	}
}
